package com.tg.base.concurrent.synch;

import com.tg.base.concurrent.SlowAction;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;

public class SynchronizedTest2 {

    private static final Map<String, String> MAP = new HashMap<>();
    private static final Integer LOCK = 1;

    private static final ExecutorService executorTomcat = Executors.newFixedThreadPool(5);
    private static final ExecutorService executorAsync = Executors.newFixedThreadPool(5);

    public static void main(String[] args) throws ExecutionException, InterruptedException, TimeoutException {
        executorTomcat.submit(invokeRequest());
        executorTomcat.submit(invokeRequest());

        TimeUnit.SECONDS.sleep(5);

        executorTomcat.submit(invokeRequest());
    }

    private static Runnable invokeRequest() {
        return () -> {
            String key = "中台客群";
            if (MAP.containsKey(key)) {
                System.out.println(Thread.currentThread().getName() + ":get -" + MAP.get(key));
            } else {
                synchronized (MAP) {

                    FutureTask<String> syncData = new FutureTask<>(() -> {
                        System.out.println(Thread.currentThread().getName() + ":working");
                        SlowAction.invoke();
                        System.out.println(Thread.currentThread().getName() + ":done");

                        return "jsonData";
                    });
                    executorAsync.submit(syncData);

                    String value = "";
                    try {
                        value = syncData.get(10, TimeUnit.SECONDS);
                    } catch (InterruptedException | ExecutionException | TimeoutException ex) {
                        ex.printStackTrace();
                    }
                    MAP.put(key, value);
                }
            }
        };
    }
}
